<template>
  <div class="login-container">
    <h1 class="title">售后服务中心</h1>
    <el-card class="form-card">
      <h2 class="title">用户登录</h2>
      <el-form
        ref="loginFormRef"
        :model="form"
        :rules="rules"
        label-width="80px"
        class="form-content"
      >
        <el-form-item label="账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="isLoading" @click="handleLogin" class="submit-btn">
            登录
          </el-button>
        </el-form-item>
        <div class="register-tip">
          还没有账号？<router-link to="/register">立即注册</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/stores/user'
import { loginUser } from '@/api/user'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const form = ref({
  account: '',
  password: '',
})
const isLoading = ref(false)
const loginFormRef = ref(null)

const rules = {
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}

const handleLogin = async () => {
  await loginFormRef.value.validate(async (valid) => {
    if (!valid) return
    isLoading.value = true
    try {
      const res = await loginUser(form.value)
      if (res.code === 200) {
        const userStore = useUserStore()
        await userStore.login(form.value) // 调用Pinia的login方法
        ElMessage.success('登录成功')
        // 跳转至首页（根据实际需求修改）
        router.push('/')
      } else {
        ElMessage.error(res.message)
      }
    } catch (err) {
      ElMessage.error('登录失败', err.message)
    } finally {
      isLoading.value = false
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 0 20px;
}

.form-card {
  width: 100%;
  max-width: 400px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
}

.submit-btn {
  width: 100%;
  margin-top: 10px;
}

.register-tip {
  text-align: center;
  margin-top: 20px;
  color: #606266;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .form-card {
    width: 90%;
  }
  .title {
    font-size: 20px;
  }
}
</style>
